package com.tcoiss.webservice.utils;

import com.tcoiss.common.core.enums.ErroEnums;
import com.tcoiss.common.core.exception.CustomException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES-128-ECB加解密
 */
public class AesUtils {
    /**
     * 加密
     * @param sSrc 加密字符
     * @param sKey 密钥
     */
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if(isNotNull(sSrc,sKey)){
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            //此处使用BASE64做转码功能，同时能起到2次加密的作用。
            return new Base64().encodeToString(encrypted);
        }
        throw new CustomException(ErroEnums.APIERRO.getCode(),new Object[]{},ErroEnums.APIERRO.getInfo() + "参数加密错误");
    }

    /**
     * 解密
     * @param sSrc 解密字符
     * @param sKey 解密密钥
     */
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            if(isNotNull(sSrc,sKey)){
                byte[] raw = sKey.getBytes("utf-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                //先用base64解密
                byte[] encrypted1 = new Base64().decode(sSrc);
                try {
                    byte[] original = cipher.doFinal(encrypted1);
                    String originalString = new String(original,"utf-8");
                    return originalString;
                } catch (Exception e) {
                    System.out.println(e);
                    return null;
                }
            }
            return null;
        } catch (Exception ex) {
            System.out.println(ex);
            return null;
        }
    }

    private static boolean isNotNull(String sSrc, String sKey){
        // 判断Key是否正确
        if (sKey == null) {
            throw new CustomException(ErroEnums.APIERRO.getCode(),new Object[]{},ErroEnums.APIERRO.getInfo() + "纳税人或时间戳参数为空");
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            throw new CustomException(ErroEnums.APIERRO.getCode(),new Object[]{},ErroEnums.APIERRO.getInfo() + "纳税人或时间戳参数异常");
        }
        return true;
    }

//    public static void main(String[] args) throws Exception {
//        String sSrc = "5fcFoSiB/nQM8d75SrXEvZm87prrDpt0UKaeL+eOAh0LRlFqEVtwdOs2Qhc+NSlyH2dYGotJG7VBFShk6iwzjQ=";
//        String key = "999500";
//        key = key + "1638254675";
//        sSrc = Decrypt(sSrc,key);
//        System.out.println(sSrc);
//    }

}
